import React from "react";
import {Button, Col, Divider, Form, Input, message, Modal, Radio, Row, Spin, Table, Tag} from "antd";
import moment from "moment";
import {addDict, deleteDict, getDictList, updateDict} from "../api/sysDict";
import {NavLink} from "react-router-dom";

const {TextArea} = Input;

const FormItem = Form.Item;

const SysDictForm = Form.create()( props => {

    const {form,visible,handleAdd,handleModalVisible,detail} = props;

    const okHandle = () => {
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            handleAdd(fieldsValue);
            form.resetFields();
        });
    };

    const formItemLayout = {
        labelCol: {
            sm: {span: 6},
        },
        wrapperCol: {
            sm: {span: 18},
        },
    };

    return (
        <Modal
            width={600}
            title="字典详情"
            maskClosable={false}
            visible={visible}
            okText={"保存"}
            onOk={okHandle}
            cancelText={"关闭"}
            onCancel={() => handleModalVisible(false)}
        >
            <Form className={"form_item_4 form_row_small_margin"}>
                <FormItem {...formItemLayout}
                          label="字典名称">
                    {form.getFieldDecorator('name', {
                        initialValue: detail.name,
                        rules: [{required: true, message: '不可为空'}],
                    })(
                        <Input className={"ant-col-12"}/>
                    )}
                </FormItem>

                <FormItem {...formItemLayout} label="备注">
                    {form.getFieldDecorator('remark', {
                        initialValue: detail.remark,
                        rules: [{required: true, message: '不可为空'}],
                    })(
                        <TextArea className={"ant-col-12"} rows={4}/>
                    )}
                </FormItem>

                <FormItem {...formItemLayout} label="状态">
                    {form.getFieldDecorator('status', {
                        initialValue: detail.status,
                        rules: [{required: true, message: '请选择状态'}],
                    })(
                        <Radio.Group className={"ant-col-12"}>
                            <Radio value="disable">禁用</Radio>
                            <Radio value="enable">启用</Radio>
                        </Radio.Group>
                    )}
                </FormItem>
            </Form>
        </Modal>
    )

});


class SysDict extends React.Component {

    state = {
        visible: false,
        loading: false,
        list: [],
        info: {},
        formValues: {}
    }


    columns = [{
        title: '名称',
        dataIndex: 'name',
        key: 'name',
        render: (text,record) => <NavLink to={`/sysDictItem/${record.id}/${record.name}`} target="_blank">{text}</NavLink>
    }, {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark'

    }, {
        title: '状态',
        key: 'status',
        dataIndex: 'status',
        render: text => <Tag
            color={text === 'enable' ? 'blue' : 'red'}>{text ? text === 'enable' ? '启用' : '禁用' : ''}</Tag>

    }, {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
        render: text => <span>{moment(text).format('YYYY-MM-DD HH:mm:ss')}</span>,

    }, {
        title: '更新时间',
        dataIndex: 'updateTime',
        key: 'updateTime',
        render: text => <span>{moment(text).format('YYYY-MM-DD HH:mm:ss')}</span>,
    }, {
        title: '操作',
        key: 'action',
        render: (text, record) => (
            <span>
                    <a onClick={() => this.showDictInfo(record)}>修改</a>
                    <Divider type="vertical"/>
                    <a onClick={() => this.showConfirm(record.id)}>删除</a>
                </span>
        ),
    }];

    componentDidMount() {
        document.title = '字典管理';
        this.loadPageDictList(1);
    }

    loadPageDictList = page => {
        let ret = getDictList(page, 20, this.state.formValues);
        ret.then((res) => {
            this.setState({...this.state, list: res.data.data});
        })
    }

    showDictInfo = info => {
        this.setState({...this.state, info: info, visible: true})
    }

    handleModalVisible = flag =>{
        this.setState({...this.state,info:{}, visible: flag})
}


    showConfirm = id => {
        let that = this;
        Modal.confirm({
            title: '是否确认删除？',
            okText: '确认',
            okType: 'danger',
            cancelText: '取消',
            onOk() {
                deleteDict(id).then(res => {
                    if (res.data.code === 10000) {
                        message.success('删除成功');
                        that.loadPageDictList(1);
                    } else {
                        message.error(res.data.msg);
                    }
                })
            },
        });
    };

    saveDictInfo = formData => {
        let {id} = this.state.info;

        let ret;
        if (id) {
            formData.id = id;
            ret = updateDict(formData);
        } else {
            ret = addDict(formData);
        }

        ret.then((res) => {
            message.success('保存成功！');
            this.handleModalVisible(false);
            this.loadPageDictList(1);
        });
    }

    handleSearch = e => {
        e.preventDefault();
        const {form} = this.props;
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            console.log(fieldsValue)
            this.state.formValues = fieldsValue;
            this.loadPageDictList(1);
        });
    };

    handleFormReset = () => {
        const {form} = this.props;
        form.resetFields();
        this.state.formValues = {};
        this.loadPageDictList(1);
    };

    renderSimpleForm = () => {
        const {
            form: {getFieldDecorator},
        } = this.props;
        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{md: 8, lg: 24, xl: 48}}>
                    <Col md={8} sm={24}>
                        <FormItem label="字典名称">
                            {getFieldDecorator('name')(<Input placeholder="请输入"/>)}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <span>
                          <Button type="primary" htmlType="submit">
                            查询
                          </Button>
                          <Button style={{marginLeft: 8}} onClick={this.handleFormReset}>
                            重置
                          </Button>
                        </span>
                    </Col>
                </Row>
            </Form>
        );
    }


    render() {

        let {list} = this.state;


        return (
            <div>

                <div style={{marginBottom: '40px'}}>{this.renderSimpleForm()}</div>

                <Button style={{marginBottom: '20px'}} type="primary" icon="plus" onClick={() => {
                    this.showDictInfo({});
                }}> 添加字典 </Button>

                <Spin spinning={this.state.loading} delay={500}>

                    {/* 项目列表 */}
                    <Table columns={this.columns} rowKey={record => record.id} dataSource={list.rows}/>

                </Spin>
                {/* 项目详情 */}
                <SysDictForm visible={this.state.visible} detail={this.state.info} handleAdd={this.saveDictInfo} handleModalVisible={this.handleModalVisible}/>
            </div>
        )
    }

}

// 表单控制
const _SysDict = Form.create()(SysDict);

export default _SysDict;
